
import Taro, { FC } from "@tarojs/taro"
import { View, Text, Image, ITouchEvent, Picker } from "@tarojs/components"
import { firstValueFrom, Subscription } from "rxjs";
import { debounceTime, filter, switchMap } from "rxjs/operators";
import { snapshotManager } from "@datorama/akita";
import { AtList, AtListItem } from "taro-ui"
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/icon.scss";
import { useEffect, useState } from "react";

import Login from "@/components/loginPopup";
import { useAuthFacade } from "@/hooks/useAuthFacade";
import { getLogger } from "@/utils/log";
import { onEmit } from "@/utils/rxHelpers";
import { GetMeRsp, likesDataRsp } from "@/models/response/userRsp";
import CONFIG from "@/config"
import { Org } from "@/models/Auth";
import { ORG_LOGIN } from "@/constants/user";
import storage from "@/utils/storage";
import { numFormat } from "@/utils";

import './index.scss'

export const Index: FC = () => {
  const logger = getLogger("/pages/my/index");

  const [authFacade, , userId, , orgs, userInfo] = useAuthFacade();
  //系统版本号
  const [version] = useState(CONFIG.VERSION);

  //登录弹窗组件相关状态
  const [clicked, setClicked] = useState(false);
  const [goUrl, setGoUrl] = useState('');
  const [navBarHeight, setNavBarHeight] = useState(0);//导航栏高度
  const [navHeight, setNavHeight] = useState(0);//胶囊高度
  const [topPadding, setTopPadding] = useState(0);//胶囊上边距
  const [navWidth, setNavWidth] = useState(0);//胶囊宽度 
  const [statusBarHeight, setstatusBarHeight] = useState(0);//状态栏高度 
  const [topMargin, setTopMargin] = useState(0);//高度差 
  const [showOrg, setShowOrg] = useState(false); //显示或隐藏机构选择弹框
  const [selectData, setSelectData] = useState(''); //选中的机构值
  const [optionData, setOptionData] = useState(['']); //个人的机构名称
  const [orgData, setOrgData] = useState([] as Org[]); //个人的机构信息 
  const [followData, setFollowData] = useState({} as likesDataRsp); //个人被点赞数以及关注信息 
  const [currentOrgId, setCurrentOrgId] = useState('')// 当前选择的机构Id
  const [loginStatus, setLoginStatus] = useState(false) //登录状态
  const avatarImg = ASSETS_PATH + '/default_avator.png'

  const orgLogin = storage.get(ORG_LOGIN)
  //综合判断需要授权跳转的URL
  const toEditInfo = () => {
    setClicked(true);
    // setGoUrl("/pages/my/editInfo/index");
    setGoUrl("/subPages/my/editInfo/index");
  }

  const toAttention = () => {
    setClicked(true);
    // setGoUrl("/pages/my/myAttention/index");
    setGoUrl("/subPages/my/myAttention/index");
  }

  const toFans = () => {
    setClicked(true);
    setGoUrl("/subPages/my/myFans/index");
  }

  const toServiceCenter = () => {
    setClicked(true);
    setGoUrl("/subPages/my/ServiceCenter/index");
  }

  const toStart = () => {
    setClicked(true);
    setGoUrl("/subPages/my/myStarting/index");
  }

  const toLive = () => {
    setClicked(true);
    setGoUrl("/subPages/my/myCreated/index");
  }

  const toHistory = () => {
    setClicked(true);
    setGoUrl("/subPages/my/history/index");
  }

  //这个不需要检查授权
  const toContact = () => {
    Taro.navigateTo({
      url: '/subPages/my/contactUs/index'
    })
  }

  //登录
  const logIn = () => {
    setClicked(true);
  }

  //复制版本号
  const copyVersion = (e: ITouchEvent) => {
    Taro.setClipboardData({ data: e.target.dataset.version })
  }

  //进行机构选择
  const openSelect = () => {
    setShowOrg(true)
    Taro.hideTabBar()
  }

  const onChange = (e) => {
    console.info("切换机构的结果", e)
    setSelectData(optionData[e.detail.value])
    const index = e.detail.value
    Taro.showTabBar()
    const orgId = orgData[index].orgId
    setCurrentOrgId(orgId)
    firstValueFrom(authFacade.changeOrg(orgId))
      .then(res => {
        console.warn("auth状态数据快照: ", snapshotManager.getStoresSnapshot(["auth"]))
      })
  }

  //取消机构选择
  const selectCancel = () => {
    setShowOrg(false)
    Taro.showTabBar()
  }

  const goOwnerInfo = () => {
    console.log(userId);
    Taro.navigateTo({
      url: `/subPages/my/userInformation/index?userId=${userId}`
    })

  }
  const goOrgInfo = () => {
    console.log(currentOrgId);
    Taro.navigateTo({
      // url: `/subPages/my/orgInformation/index?orgId=${orgLogin}&orgAvar=${anchorLogo || ownerLogo}&isFollowed=${isAttention}`
      url: `/subPages/my/orgInformation/index?orgId=${currentOrgId || orgLogin}`
    })
  }

  // 取得右上角胶囊高度，自定义标题与其对齐  
  useEffect(() => {
    Taro.getSystemInfo({
      success: function (res) {
        let myStatusBar = 0     // 状态栏高度
        let myCustomBar = 0  //导航栏高度
        let myNvaMartom = 0  //高度差
        let myNavHeight = 0   //胶囊高度
        let myNavWidth = 0   //胶囊宽度
        let myTopPadding = 0   //胶囊上边距 
        const custom = Taro.getMenuButtonBoundingClientRect();
        myStatusBar = res.statusBarHeight || 0;
        myNavHeight = custom.height
        myNavWidth = custom.width
        myTopPadding = custom.top
        myNvaMartom = custom.top - myStatusBar;
        myCustomBar = (myNvaMartom * 2 + custom.height)
        setNavBarHeight(myCustomBar)
        setNavHeight(myNavHeight)
        setstatusBarHeight(myStatusBar)
        setTopMargin(myNvaMartom)
        setTopPadding(myTopPadding)
        setNavWidth(myNavWidth)
      }
    })
  }, [navBarHeight])

  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      onEmit<GetMeRsp>(
        authFacade.loginStatus$
          .pipe(
            filter(status => status === true),
            debounceTime(500),
            switchMap(authFacade.getMe)
          ),
        res => {
          const arr = res.orgList
          const data = Object.assign({}, { likes: res.likes, follows: res.follows, following: res.following })
          setFollowData(data)
          setOrgData(arr)
          const item = arr.map(value => value.orgName)
          setOptionData(item)
          const orgsData = arr.filter(item1 => item1.orgId === storage.get(ORG_LOGIN))
          orgsData.length > 0 && setSelectData(orgsData[0].orgName)
          setLoginStatus(true)
        },
        err => logger.ERROR("获取个人信息错误", err)
      ),
    ]

    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [])

  return (
    <View className='index' >
      <View className='top' >
        <View className='topNav' style={{ height: navBarHeight + 'px', top: statusBarHeight + 'px' }}>
          <View className='navBox' style={{ height: navHeight + 'px', top: topMargin }}>
            <View className='orgName' >
              {
                orgData && orgData.length > 0 && (
                  <View className='pick'>
                    <Picker mode='selector' range={optionData} onChange={onChange} onClick={openSelect} onCancel={selectCancel} >
                      <AtList className='select'>
                        <AtListItem
                          title={selectData == '' ? '机构选择' : selectData}
                        />
                      </AtList>
                    </Picker>
                    <View className='down'><Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/down1.png' className='down_img'></Image></View>
                  </View>
                )
              }
            </View>
          </View>
        </View>
        <View className='top_main' style={{ marginTop: (statusBarHeight + navBarHeight) + 'px' }}>
          <View className='tx' onClick={toEditInfo}>
            <Image src={userInfo.avatarUrl == '' ? avatarImg : userInfo.avatarUrl} className='tx_img'></Image>
          </View>
          {
            loginStatus && (
              <View className='border'>
                <View className='border-top' >
                  <View className='top-info'>
                    <View className='nikname' onClick={toEditInfo}>{userInfo.nickName}</View>
                    {/* 新增个人/机构主页入口 */}
                    <View className='org-info'>
                      <View onClick={goOwnerInfo}>个人主页</View>
                      {(!!orgLogin || !!currentOrgId) && (<View onClick={goOrgInfo}>机构主页</View>)}
                    </View>
                  </View>
                  <View className='edit' onClick={toEditInfo}>编辑信息</View>
                </View>
                <View className='info'>
                  <View className='total' >总点赞数: {numFormat(followData.likes)}</View>
                  <View className='line'> </View>
                  <View className='follow' onClick={toAttention}>关注: {numFormat(followData.follows)}</View>
                  <View className='line'> </View>
                  <View className='fans'>粉丝: {numFormat(followData.following)}</View>
                </View>
              </View>
            )
          }

          {
            !loginStatus && (
              <View className='logon' onClick={logIn}>登陆</View>
            )
          }
        </View>
      </View>
      <View className='main'>
        <AtList>
          <AtListItem
            title='服务中心'
            // thumb='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/serveCenter.svg'
            thumb={ASSETS_PATH + '/my_Server.png'} onClick={toServiceCenter}
          />
          <AtListItem
            title='即将开播'
            // thumb='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/like.svg'
            thumb={ASSETS_PATH + '/my_LiveSoon.png'}

            onClick={toStart}
          />
          <AtListItem
            title='我的直播'
            // thumb='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/zb.svg'
            thumb={ASSETS_PATH + '/my_Live.png'}

            onClick={toLive}
          />
          <AtListItem
            title='观看历史'
            // thumb='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/clok.svg'
            thumb={ASSETS_PATH + '/my_history.png'}

            onClick={toHistory}
          />
          <AtListItem
            title='联系我们'
            // thumb='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/lianxi.svg'
            thumb={ASSETS_PATH + '/my_contact.png'}
            onClick={toContact}
          />
        </AtList>
      </View>
      <View className='version-tip'>
        <Text onClick={copyVersion} data-version={version}>{version}</Text>
      </View>
      {/* {
        showOrg && (
          <View className='selectorBox'>
            <View className='contentBox'> 
              <ScrollView scrollY className='select'>
                {
                  optionData.map((item, index) =>
                    <View className='option' key={index}>{item}</View>
                  )
                }
              </ScrollView>
              <View className='border1'></View>
              <View className='cancel' onClick={selectCancel}>取消</View>
            </View>
          </View>
        )
      }  */}

      <Login goUrl={goUrl} setGoUrl={setGoUrl} clicked={clicked} setClicked={setClicked} />
    </View>
  )
}

export default Index
